import { doLoginByUserNameAndPassword, getUserInfo } from '../services/API';
import { routerRedux } from 'dva/router';
import { setLoginToken, clearLoginToken, clearMenu } from '../utils/utils';

export default {
  namespace: 'login',
  state: {
    userInfo: null,
    status: null
  },
  effects: {
    // 登录
    *doLogin({ payload: loginData }, { call, put }) {
      const loginResult = yield call(doLoginByUserNameAndPassword, loginData);
      if (loginResult && loginResult.code === 200) {
        // console.log("用户" + loginData.userName + "登录成功");
        // 这里需要获取用户的token，然后写入本地浏览器中,同时还需要根据用户信息获取对应的菜单进行渲染
        setLoginToken(loginResult.token);
        yield put(routerRedux.push('/'));
        yield put({ type: 'test' }); //获取用户信息
      } else {
        console.log('doLogin fail', loginResult);
        // yield put({ type: "showMessage", status: "error" });
      }
    },
    // 等出
    *doLogout(payload, { put }) {
      // console.log("系统退出");
      // const result = yield call(logout);
      // console.log(result);
      clearLoginToken();
      clearMenu();
      localStorage.removeItem('userInfo');
      yield put(routerRedux.push('/login'));
    },
    // 获取用户信息
    *test(payload, { call, put }) {
      // console.log("测试数据");
      const result = yield call(getUserInfo);
      if (result.code === 200) {
        yield put({ type: 'showMessage', userInfo: result.user });
        localStorage.setItem('userInfo', JSON.stringify(result.user));
      }
      // console.log("获取返回数据");
      // console.log(result);
    }
  },

  reducers: {
    //显示错误消息
    showMessage(state, { status, userInfo }) {
      return {
        ...state,
        status: status,
        userInfo: userInfo
      };
    }
  }
};
